package main

import "fmt"

/*
map[keyType]valueType
其中：

keyType：表示键的类型，可以是任何可比较的类型（如整型、浮点型、字符串、指针、接口等），但不能是函数、切片、map 或包含不可比较类型的结构体。
valueType：表示值的类型，可以是任何 Go 语言支持的类型。
*/

func main() {
	//map的声明
	var mapLit map[string]int
	var mapAssigned map[string]int

	//初始化
	mapLit = map[string]int{"one": 1, "two": 2}
	//make初始化
	mapCreated := make(map[string]int)
	mapAssigned = mapLit

	mapCreated["key"] = 10
	mapCreated["key1"] = 11
	mapAssigned["key2"] = 12
	fmt.Println(mapLit)
	fmt.Println(mapCreated)
	fmt.Println(mapAssigned)
	fmt.Printf("map lit at one is:%d\n", mapLit["one"])
	fmt.Printf("map lit at two is:%d\n", mapLit["two"])
	fmt.Printf("map lit at three is:%d\n", mapLit["three"])
	fmt.Printf("map lit at key is:%d\n", mapCreated["key"])

	//map func
	mf := map[int]func() int{
		1: func() int {
			return 10
		},
		2: func() int {
			return 20
		},
		3: func() int {
			return 30
		},
		5: func() int {
			return 50
		},
	}

	fmt.Println(mf)

	//map 容量
	m := make(map[string]int, 3)
	fmt.Println(len(m))
	//当map增长到容量上限时，在增加新的key-value对时，会自动扩容，大小自动+1
	for i := 0; i < 10; i++ {
		m[fmt.Sprintf("key%d", i)] = i
	}
	fmt.Println(len(m))
	//用切片作为map的值
	mp1 := make(map[int][]int)
	mp2 := make(map[int]*[]int) //指针不能指向临时变量，需要先初始化
	slice := []int{1, 2, 3}
	mp1[1] = []int{1, 2, 3}
	mp1[2] = []int{4, 5, 6}
	mp2[1] = &slice
	fmt.Println(mp1)
	fmt.Println(mp2)
	//delete map
	delete(mp1, 1)
	value, isPresent := mp1[1]
	if isPresent {
		fmt.Println(value)
	} else {
		fmt.Println("not present")
	}
	map1 := make(map[int]float32)
	map1[1] = 1.0
	map1[2] = 2.0
	map1[3] = 3.0
	map1[4] = 4.0
	for k, v := range map1 {
		fmt.Printf("key:%d,value:%f\n", k, v)
	}
	// map类型切片
	items := make([]map[int]int, 5)
	for i := range items {
		items[i] = make(map[int]int, 1)
		items[i][1] = 2
	}
	fmt.Println(items)

}
